package kz.kstu.scantest.business.client.config;

import org.apache.log4j.Logger;

import java.io.*;
import java.net.URL;
import java.util.Properties;

/**
 * @author Filipp_Stankevich
 *         created: 23.09.11 21:01
 */
public class Configuration {

    public final static String HOST_PARAM_NAME = "host";

    public final static String PORT_PARAM_NAME = "port";

    public final static String MODE_PARAM_NAME = "mode";

    public final static String DEBUG_MODE_PARAM_VALUE = "debug";

    private final static Logger LOGGER = Logger.getLogger(Configuration.class);

    public static final String CONFIG_FILE_PATH = "conf/config.properties";

    private static Configuration instance;
    private Properties properties = new Properties();

    private Configuration() {
    }

    public static Configuration getInstance() {
        if (instance == null) {
            instance = new Configuration();
            instance.readProperties();
        }
        return instance;
    }

    public String getParameter(String paramName) {
        return properties.getProperty(paramName);
    }

    private void readProperties() {
        try {
            File propertiesFile = new File(getAppPathDir(), CONFIG_FILE_PATH);
            properties.load(new FileInputStream(propertiesFile));
        } catch (FileNotFoundException e) {
            LOGGER.error("Configuration file not found, file path = " + CONFIG_FILE_PATH, e);
        } catch (IOException e) {
            LOGGER.error("Can not continueRead configuration file, file path = " + CONFIG_FILE_PATH, e);
        }
    }

    public static String getAppPathDir() {
        URL jarUrl = Configuration.class.getProtectionDomain().getCodeSource().getLocation();
        File jar = new File(jarUrl.getFile());
        File jarDir = jar.getParentFile();
        File applicationDir = jarDir.getParentFile();
        return applicationDir.getPath();
    }

    public boolean isDebugMode() {
        String modeValue = getParameter(MODE_PARAM_NAME);
        return Configuration.DEBUG_MODE_PARAM_VALUE.equalsIgnoreCase(modeValue);
    }
}
